package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.BusinessTool;
import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.Tool;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;

import javax.script.ScriptException;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目附件
 */
@BusinessDataConverter(
        insertSql = "insert into nd_project_affix (ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, PROJECT_ID, FILE_NAME, STORE_TYPE, FILE_SIZE, SUBMITTER, FILE_CONTENT, FILE_REMARK, FILE_URL, AFFIX_TYPE, MODULE_ID, FILE_TYPE, AFFIX_SOURCE, BIZ_TYPE, IS_DELETE, TASK_ID, JOB_ID, IS_VALID, LETTER_NUM, CONTRACT_NUM, PROJECT_ATTACHMENT_TYPE)" +
                "values (?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        updateSql = "UPDATE nd_project_affix SET CREATE_NAME = ?,CREATE_BY = ?,CREATE_DATE = ?,UPDATE_NAME = ?,UPDATE_BY = ?,UPDATE_DATE = ?,SYS_ORG_CODE = ?,SYS_COMPANY_CODE = ?,BPM_STATUS = ?," +
            "PROJECT_ID = ?,FILE_NAME = ?,STORE_TYPE = ?,FILE_SIZE = ?,SUBMITTER = ?,FILE_CONTENT = ?,FILE_REMARK = ?,FILE_URL = ?,AFFIX_TYPE = ?,MODULE_ID = ?,FILE_TYPE = ?,AFFIX_SOURCE = ?," +
            "BIZ_TYPE = ?,IS_DELETE = ?,TASK_ID = ?,JOB_ID = ?,IS_VALID = ?,LETTER_NUM = ?,CONTRACT_NUM = ?,PROJECT_ATTACHMENT_TYPE = ? WHERE ID = ?",
        findMigratedIdListSql = "SELECT ID FROM nd_project_affix WHERE PROJECT_ID = ?",
        seq = 600
)
public class NdProjectAffix extends AbstractBusiness {

  public NdProjectAffix(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId);
  }

  @Override
  public void migrate() throws Exception {
    List<Map> BtEnterpriseInquiryDatumList = this.sourceData.getBtEnterpriseInquiryDatumList();
    Map btItemBasic = this.sourceData.getBtItemBasic().get(0);
    for (Map btEnterpriseInquiryDatum : BtEnterpriseInquiryDatumList) {
      try {
        String sourceId = btEnterpriseInquiryDatum.get("DOCNO").toString();
        int needMigratedResult = this.needMigrated(sourceId);
        if (needMigratedResult == 0) {
          continue;
        }

        // 单条插入或更新
        if (needMigratedResult == 1) {
          this.targetDbUtil.updateByParams(updateSql, this.buildValues(btEnterpriseInquiryDatum, btItemBasic), true);
          // 批量插入或更新 和 单条插入或更新 二选一
//             this.batchUpdateValues.add(this.buildValues(row));
        } else {
          this.targetDbUtil.updateByParams(insertSql, this.buildValues(btEnterpriseInquiryDatum, btItemBasic));
          // 批量插入或更新 和 单条插入或更新 二选一
//             this.batchInsertValues.add(this.buildValues(row));
        }

      } catch (Exception e) {
          if(e.getMessage().contains("C0033801") || e.getMessage().contains("违反唯一约束条件")){
            continue;
          }
        throw new Exception(String.format("项目附件[%s]迁移失败:%s\n", btEnterpriseInquiryDatum.get("ITEMNO"), e.getMessage()));
      }
    }

    this.migrateOther();
  }

  public List buildValues(Map btEnterpriseInquiryDatum, Map btItemBasic) throws SQLException, ScriptException {
    List values = new ArrayList();
    String empCode = BusinessTool.getTaskRealActorId(btEnterpriseInquiryDatum.get("EMPCODE").toString(),btEnterpriseInquiryDatum.get("CREATE_TIME"));
    //ID
    values.add(btEnterpriseInquiryDatum.get("DOCNO").toString());
    //CREATE_NAME	创建人名称
    values.add(BusinessTool.getEmpNameByEmpCode(empCode));
    //CREATE_BY	创建人登录名称
    values.add(empCode);
    //CREATE_DATE	创建日期
    values.add(btEnterpriseInquiryDatum.get("CREATE_TIME"));
    //UPDATE_NAME	更新人名称
    values.add(null);
    //UPDATE_BY	更新人登录名称
    values.add("jwfile");
    //UPDATE_DATE	更新日期
    values.add(btEnterpriseInquiryDatum.get("MODIFY_TIME"));
    //SYS_ORG_CODE	所属部门
    values.add(null);
    //SYS_COMPANY_CODE	所属公司
    values.add(null);
    //BPM_STATUS	流程状态
    values.add("1");
    //PROJECT_ID	项目id
    values.add(btItemBasic.get("ITEMNO"));
    //FILE_NAME	文件名称
    values.add(btEnterpriseInquiryDatum.get("ELEFILENAME"));
    // STORE_TYPE	存储形式(电子件、原纸件、复印件) 字典
    values.add(Tool.covertToBigDecimal(btEnterpriseInquiryDatum.get("DOCTYPE")));
    //FILE_SIZE	文件大小
    if(btEnterpriseInquiryDatum.get("ELEFILESIZE") == null || btEnterpriseInquiryDatum.get("ELEFILESIZE").toString().equals("") ){
      values.add(null);
    } else {
      try {
        BigDecimal originalFileSize = BigDecimal.valueOf(Long.parseLong(btEnterpriseInquiryDatum.get("ELEFILESIZE").toString()));
        values.add(originalFileSize.divide(BigDecimal.valueOf(1024*1024)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
      }catch(Exception e) {
        values.add(null);
      }
    }
    //SUBMITTER	提交人
    values.add(BusinessTool.getEmpNameByEmpCode(Tool.removeOrgCodeFromEmpCode(btEnterpriseInquiryDatum.get("EMPCODE").toString())));
    //FILE_CONTENT	文件内容
    values.add(null);
    //FILE_REMARK	文件备注
    values.add(Tool.decodeUnicode(btEnterpriseInquiryDatum.get("DOCREMARK")));
    //FILE_URL	文件路径
    values.add(btEnterpriseInquiryDatum.get("ELEFILESTORENAME"));
    //AFFIX_TYPE	附件种类
    values.add(null);
    //MODULE_ID	模块id
    values.add(null);
    //FILE_TYPE	文件格式
    values.add(Tool.removeFileTypeCode(btEnterpriseInquiryDatum.get("ELEFILENAME")));
    //AFFIX_SOURCE	附件来源
    values.add(null);
    //BIZ_TYPE	业务类型
    String bizType = null;
    if (btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("1") || btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("3")) {
      bizType = "xmsp";
    } else if (btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("2")) {
      bizType = "cwsjzl";
    } else if (btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("4")) {
      bizType = "xmws";
    } else if (btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("5")) {
      bizType = "dcfj";
    } else if (btEnterpriseInquiryDatum.get("INQUIRYTYPE").toString().equals("6")) {
      bizType = "zcssfj";
    }
    values.add(bizType);
    //IS_DELETE	删除标志
    values.add(0);
    //TODO: TASK_ID	任务id 临时存储原 INQUIRYTYPE 字段数据
    values.add(btEnterpriseInquiryDatum.get("INQUIRYTYPE"));
    //JOB_ID	流程实例id
    values.add(btEnterpriseInquiryDatum.get("WORKFLOWNO") == null ? null :btEnterpriseInquiryDatum.get("WORKFLOWNO")+"-JW");
    //IS_VALID	是否使用
    values.add("Y");
    //LETTER_NUM	序号编码
    values.add(null);
    //CONTRACT_NUM	合同编码
    values.add(btEnterpriseInquiryDatum.get("CONTRACTSERIALNO"));
    //PROJECT_ATTACHMENT_TYPE	项目附件类型0：无区分 1：基础资料  2：征信资料  3：土地流转资料
    values.add(1);
    return values;
  }

  public void migrateOther() throws Exception {
    //归档附件
    List<Map> btitemBasicDatumList = this.sourceData.getBtItemBasicDatumList().stream()
        .filter(btItemBasicDatum -> {
          Object elefname = btItemBasicDatum.get("ELEFILESTORENAME");
         if(elefname == null){
           return false;
         }
         return !elefname.toString().equals("");
        })
        .collect(Collectors.toList());

    //归档附件表(流程)
    List<Map> btitemDatumSubmit = this.sourceData.getBtItemDatumSubmitList().stream()
        .filter(btItemDatumSubmit -> {
          Object elefname = btItemDatumSubmit.get("ELEFILESTORENAME");
          if(elefname == null){
            return false;
          }
          return !elefname.toString().equals("");
        })
        .collect(Collectors.toList());

    //台账附件表
    List<Map> btItemAccountDetailList = this.sourceData.getBtItemAccountDetailList().stream()
        .filter(btItemAccountDetail -> {
          Object elefname = btItemAccountDetail.get("ELEFILESTORENAME");
          if(elefname == null){
            return false;
          }
          return !elefname.toString().equals("");
        })
        .collect(Collectors.toList());

    //台账附件表(流程)
    List<Map> btItemItemChargeList = this.sourceData.getBtItemChargeAuditList().stream()
        .filter(btItemItemCharge -> {
          Object elefname = btItemItemCharge.get("ELEFILESTORENAME");
          if(elefname == null){
            return false;
          }
          return !elefname.toString().equals("");
        })
        .collect(Collectors.toList());

    // 电子发票表
    List<Map> btItemInvoiceList = this.sourceData.getBtItemInvoice().stream()
        .filter(btItemInvoice -> {
          Object elefname = btItemInvoice.get("EIVFILESTORENAME");
          if(elefname == null){
            return false;
          }
          return !elefname.toString().equals("");
        })
        .map(btItemInvoice->{
          Map map = new HashMap<String,Object>();
          map.put("ELEFILESTORENAME",btItemInvoice.get("EIVFILESTORENAME"));
          map.put("ELEFILESIZE",btItemInvoice.get("EIVFILESIZE"));
          map.put("ELEFILENAME",btItemInvoice.get("EIVPRONAME")+"." + btItemInvoice.get("EIVFILETYPE"));
          return map;
        })
        .collect(Collectors.toList());

    btitemBasicDatumList.addAll(btitemDatumSubmit);
    btitemBasicDatumList.addAll(btItemAccountDetailList);
    btitemBasicDatumList.addAll(btItemItemChargeList);
    btitemBasicDatumList.addAll(btItemInvoiceList);

    for (Map btItem : btitemBasicDatumList) {
      try {
        String targetId = btItem.get("ELEFILESTORENAME").toString().replace("-","");
        int needMigratedResult = this.needMigrated(targetId);
        if (needMigratedResult == 0) {
          continue;
        }
        ;
        // 单条插入或更新
        if (needMigratedResult == 1) {
          this.targetDbUtil.updateByParams(updateSql, this.buildValuesOther(btItem), true);
          // 批量插入或更新 和 单条插入或更新 二选一
//             this.batchUpdateValues.add(this.buildValues(this.buildValuesOther(btItem)));
        } else {
          this.targetDbUtil.updateByParams(insertSql, this.buildValuesOther(btItem));
          // 批量插入或更新 和 单条插入或更新 二选一
//             this.batchInsertValues.add(this.buildValues(this.buildValuesOther(btItem)));
        }

      } catch (Exception e) {
        throw new Exception(String.format("项目附件[%s]迁移失败:%s\n", btItem.get("ITEMNO"), e.getMessage()));
      }
    }
  }

  public List buildValuesOther(Map businessData) throws ScriptException {
    String businessFileId = businessData.get("ELEFILESTORENAME").toString().replace("-","");
    String[] originalFileNameArr = businessData.get("ELEFILENAME").toString().split("\\.");
    List values = new ArrayList();
    // ID
    values.add(businessFileId);
    // CREATE_NAME
    values.add(null);
    // CREATE_BY
    values.add(null);
    // CREATE_DATE
    values.add(null);
    // UPDATE_NAME
    values.add(null);
    // UPDATE_BY
    values.add("jwfile");
    // UPDATE_TIME
    values.add(null);
    // TODO:SYS_ORG_CODE
    values.add(null);
    // SYS_COMPANY_CODE
    values.add("002");
    //BPM_STATUS
    values.add(1);
    //PROJECT_ID
    values.add(this.projectId);
    //FILE_NAME
    values.add(businessData.get("ELEFILENAME"));
    // STORE_TYPE 存储形式(电子件、原纸件、复印件)
    values.add(businessData.get("DOCTYPE"));
    // FILE_SIZE (MB) 保留两位小数
    if(businessData.get("ELEFILESIZE") == null || businessData.get("ELEFILESIZE").toString().equals("") ){
      values.add(null);
    } else {
      try {
        BigDecimal originalFileSize = BigDecimal.valueOf(Long.parseLong(businessData.get("ELEFILESIZE").toString()));
        values.add(originalFileSize.divide(BigDecimal.valueOf(1024*1024)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
      }catch(Exception e) {
        values.add(null);
      }
   }
    // SUBMITTER
    values.add(null);
    // FILE_CONTENT
    values.add(null);
    // FILE_REMARK
    values.add(businessData.get("DOCREMARK") == null ? null : Tool.decodeUnicode(businessData.get("DOCREMARK").toString()));
    // FILE_URL
    values.add(businessData.get("ELEFILESTORENAME").toString());
    // AFFIX_TYPE
    values.add(null);
    // MODULE_ID
    values.add(null);
    // FILE_TYPE
    values.add(originalFileNameArr[originalFileNameArr.length - 1]);
    // TODO:AFFIX_SOURCE
    values.add(null);
    // BIZ_TYPE
    values.add("jwhidden");
    // IS_DELETE
    values.add(0);
    // TASK_ID
    values.add(null);
    // JOB_ID
    values.add(null);
    // IS_VALID
    values.add(null);
    // LETTER_NUM
    values.add(null);
    // CONTRACT_NUM
    values.add(null);
    // PROJECT_ATTACHMENT_TYPE(1:基础资料 2:征信资料 3:土地资料)
    values.add(1);
    return values;
  }

  public void customMigrate(List values) throws Exception {
    int needMigratedResult = this.needMigrated(values.get(0).toString());
    if (needMigratedResult == 0) {
      return;
    }
    // 单条插入或更新
    if (needMigratedResult == 1) {
        this.targetDbUtil.updateByParams(updateSql, values, true);
        // 批量插入或更新 和 单条插入或更新 二选一
//        this.batchUpdateValues.add(values);
      } else {
        this.targetDbUtil.updateByParams(insertSql, values);
        // 批量插入或更新 和 单条插入或更新 二选一
//             this.batchInsertValues.add(values);
      }
  }

  public void customStart() throws SQLException {
    System.out.println("开始迁移"+this.getClass().getSimpleName()+"表(流程)...");
    if(this.batchUpdateValues.size() > 0) {
      this.targetDbUtil.updateByParamsBatch(this.updateSql, this.batchUpdateValues, true);
    }
    if(this.batchInsertValues.size() > 0) {
      this.targetDbUtil.updateByParamsBatch(this.insertSql, this.batchInsertValues, false);
    }
    System.out.println(this.getClass().getSimpleName()+"表(流程)迁移完成.");
  }
}



